
from functools import wraps
DEFAULT_EXCEPTIONS = (Exception,)


def retry(tries, exceptions=None):
    """
    Decorator for retrying a function if exception occurs
    tries -- num tries
    exceptions -- exceptions to catch
    """
    def wrap(f):
        @wraps(f)
        def fn(*args, **kwargs):
            for _ in range(tries):
                try:
                    return f(*args, **kwargs)
                except exceptions or DEFAULT_EXCEPTIONS, e:
                    exception = e
            raise exception
        return fn
    return wrap


if __name__ == "__main__":
    @retry(2)
    def fail_fn():
        raise Exception("failed")
    print fail_fn.__name__
    fail_fn()
